package com.soul.dj.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.soul.dj.MainApplication;
import com.soul.dj.util.http.*;
import com.soul.dj.util.http.MediaType;
import com.soul.dj.util.http.json.JsonProcessUtil;
import okhttp3.*;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 *
 * @author SOUL 2016/07/07
 */
public abstract class BaseActivity extends FragmentActivity implements OnClickListener {

    protected static final String TAG = Package.class.getName();
    private OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)      //设置连接超时
            .readTimeout(60, TimeUnit.SECONDS)         //设置读超时
            .writeTimeout(60, TimeUnit.SECONDS)        //设置写超时
            .retryOnConnectionFailure(true)            //是否自动重连
            .build();
    protected InputMethodManager inputMethodManager;

    private Dialog dialog;

    private boolean progressEnabled = true;



    public void setProgressEnabled(boolean progressEnabled) {
        this.progressEnabled = progressEnabled;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        super.onCreate(savedInstanceState);
        MainApplication.addActivity(this);
        if (!isTaskRoot()) {
            Intent intent = getIntent();
            String action = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER)
                    && action.equals(Intent.ACTION_MAIN)) {
                MainApplication.removeActivity(this);
                return;
            }
        }
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
    }

    protected abstract void initView();

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onClick(View v) {

    }

    protected void getFullscreen() {
        // 全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注：回调 1
        // Bugtags.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注：回调 2
        // Bugtags.onPause(this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // 注：回调 3
        // Bugtags.onDispatchTouchEvent(this, event);
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (this instanceof MainActivity) {
                MainApplication.exit(getActivity());
                return false;
            } else {
                MainApplication.removeActivity(this);
            }
        }

        return super.onKeyDown(keyCode, event);
    }


    public boolean httpPrepare() {
        boolean avl = NetWorkUtils.isNetworkAvailable(getActivity());

        if (!avl) {
            closeDialog();
            // this.onAjaxError("您的手机网络已断开，请连接后重试。", tag);
            AlertDialogUitls.alert(getActivity(),"提示", "您的手机网络已断开，请连接后重试。", new String[] { "确定" },
                   errorDialogClicklistener);
        }

        return avl;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected void sendHttp(Constants.HTTP method, String url, RequestBody params,
                            JSONCallBack callback) {
        showDialog();

        Request request = null;
        if (method == Constants.HTTP.GET) {
            request = new Request.Builder().url(url).get().build();
        } else if (method == Constants.HTTP.POST) {
            request = new Request.Builder().url(url).post(params).build();
        }
        //3,创建一个call对象
        Call call = mOkHttpClient.newCall(request);
        //4,将请求添加到调度中
        call.enqueue(callback);
    }

    @SuppressWarnings("rawtypes")
    protected void sendHttp(String url, okhttp3.MediaType mediaype, Map<String,Object> paramsMap, JSONCallBack callback) {
        if (!httpPrepare()) {
            return;
        }
        try{
        Log.d("HttpProcessor:",
                "请求url:" + url + "\n请求参数:" + JsonProcessUtil.beanToJson(paramsMap));
            RequestBody body = RequestBody.create(mediaype, JsonProcessUtil.beanToJson(paramsMap));
            sendHttp(Constants.HTTP.POST, url, body, callback);
        }catch (Exception e){
            e.printStackTrace();
            Log.e("yhbsoul",e.getMessage());
        }
    }
    @SuppressWarnings("rawtypes")
    protected void sendHttpFiles(String url, Map<String,Object> paramsMap,String fileKey, List<String> fileList, JSONCallBack callback) {
        try{
            if (!httpPrepare()) {
                return;
            }
            Log.d("HttpProcessor:",
                "请求url:" + url + "\n请求参数:" + JsonProcessUtil.beanToJson(paramsMap)+ JsonProcessUtil.beanToJson(fileList));



            MultipartBody.Builder buider = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (String path : fileList ) {
                File file = new File(path);
                RequestBody fileBody = RequestBody.create(MediaType.getMimeType(file.getName()), file);
                buider.addFormDataPart(fileKey , file.getName() , fileBody);
            }
            for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
                buider.addFormDataPart(entry.getKey(),entry.getValue().toString());
            }

            sendHttp(Constants.HTTP.POST, url,buider.build(), callback);
        }catch (Exception e){
            e.printStackTrace();
            Log.e("yhbsoul",e.getMessage());
        }
    }

    /**
     * 显示Dialog
     */
    private void showDialog() {
        if (progressEnabled) {
            if (dialog == null) {
                dialog = LoadingDialog.createLoadingDialog(this, "正在加载中...");
                dialog.show();
            }
        }
    }

    public Activity getActivity() {
        Class activityThreadClass = null;
        try {
            activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭Dialog
     */
    private void closeDialog() {
        if (progressEnabled) {
            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }
        }
    }


    public void onErrorDialogClick() {

    }

    protected DialogInterface.OnClickListener errorDialogClicklistener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            onErrorDialogClick();
        }
    };

    public void onAjaxError(String tag) {
        closeDialog();
        AlertDialogUitls.alert(getActivity(),"提示", "数据加载异常，请确认您的手机网络畅通！", new String[] { "确定" },
                errorDialogClicklistener);
    }

    protected void showKeyboard() {
        View v = getCurrentFocus();

        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        if (imm != null && v != null) {

            imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);

        }
    }

    protected void hideKeyboard() {
        View v = getCurrentFocus();

        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        if (imm != null && v != null) {

            imm.hideSoftInputFromWindow(v.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);

        }
    }

    public void onAjaxFail(String code, String title,String str, String tag) {
        closeDialog();
        if (TextUtils.equals(code,"-200")){
            startActivity(new Intent(this, LoginActivity.class));
            MainApplication.clearMap();
            MainApplication.removeActivity(this);
        }else{
            toast(str);
        }

    }


    public void onAjaxOK(Object result, String tag) {
        closeDialog();
    }


    protected void toast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

}
